from SearchapiController import SearchAPI


def create_index(self, index_name="ott", index_type="ott_type"):
    '''
    创建索引,创建索引名称为ott，类型为ott_type的索引
    :param ex: Elasticsearch对象
    :return:
    '''
    # 创建映射
    _index_mappings = {
        "mappings": {
            self.index_type: {
                "properties": {
                    "title": {
                        "type": "text",
                        "index": True,
                        "analyzer": "ik_max_word",
                        "search_analyzer": "ik_max_word"
                    },
                    "date": {
                        "type": "text",
                        "index": True
                    },
                    "keyword": {
                        "type": "string",
                        "index": "not_analyzed"
                    },
                    "source": {
                        "type": "string",
                        "index": "not_analyzed"
                    },
                    "link": {
                        "type": "string",
                        "index": "not_analyzed"
                    }
                }
            }
        }
    }
    if self.es.indices.exists(index=self.index_name) is not True:
        res = self.es.indices.create(index=self.index_name, body=_index_mappings)
        print(res)

def Index_Data(cls):
    '''
    数据存储到es
    :return:
    '''
    with open('/Users/zhuangshilin/Documents/碳数据文件/carbon_news.json', "r") as f:
        for line in f.readlines():
            line = line.strip('\n')  # 去掉列表中每一个元素的换行符
            print(line)
    list = [
        {"date": "2017-09-13",
         "source": "慧聪网",
         "link": "http://info.broadcast.hc360.com/2017/09/130859749974.shtml",
         "keyword": "电视",
         "title": "付费 电视 行业面临的转型和挑战"
         },
        {"date": "2017-09-13",
         "source": "中国文明网",
         "link": "http://www.wenming.cn/xj_pd/yw/201709/t20170913_4421323.shtml",
         "keyword": "电视",
         "title": "电视 专题片《巡视利剑》广获好评：铁腕反腐凝聚党心民心"
         }
    ]
    # 标准化doc_type应该是index_type，但一开始命名为 doc，故针对该网站搜索节点更改为doc
    with open('json', "w") as f:
        list = f.readline()
        print(list)
    for item in list:
        res = cls.es.index(index=cls.index_name, doc_type=cls.index_type, body=item)
        print(res['created'])


if __name__ == "__main__":
    # SearchAPI.Index_Data()
    with open('/Users/zhuangshilin/Documents/碳数据文件/carbon_news.json', "r") as f:
        for line in f.readlines():
            line = line.strip('\n')  # 去掉列表中每一个元素的换行符
            print(line)

